<template>
  <div>
    <el-dialog v-model="visible" :fullscreen="props.fullscreen" class="base-dialog" v-bind="$attrs" v-on="attrs">
      <slot></slot>

      <template #header>
        <div class="header">
          <span>{{ $attrs.title || "标题" }}</span>
          <el-icon class="icon" @click="emit('update:fullscreen', !props.fullscreen)">
            <template v-if="props.fullscreen">
              <Connection />
            </template>

            <template v-else>
              <FullScreen />
            </template>
          </el-icon>
        </div>
      </template>

      <template #footer>
        <slot name="footer">
          <div class="dialog-footer">
            <el-button @click="handleBtnClose" size="small">取 消</el-button>
            <el-button :loading="loading" type="primary" @click="handleBtnConfirm" size="small">确 定</el-button>
          </div>
        </slot>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch, useAttrs } from "vue";
import { FullScreen, Connection } from "@element-plus/icons-vue";

type Props = {
  modelValue: boolean;
  fullscreen: boolean;
};

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  fullscreen: false
});

const loading = ref(false);
const attrs = useAttrs();
const emit = defineEmits(["update:modelValue", "update:fullscreen", "btnConfirm", "btnClose"]);

const visible = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  }
});

watch(
  () => props.fullscreen,
  val => {
    emit("update:fullscreen", val);
  },
  { immediate: true }
);

const handleBtnConfirm = () => {
  loading.value = true;
  emit(
    "btnConfirm",
    () => (loading.value = false),
    () => {
      loading.value = false;
      emit("update:modelValue", false);
    }
  );
};

const handleBtnClose = () => {
  emit("btnClose", () => {
    loading.value = false;
    emit("update:modelValue", false);
  });
};
</script>

<style lang="scss">
.base-dialog {
  .el-dialog__header {
    margin: 0;
    min-height: 20px;
    border-bottom: 1px solid #f0f0f0;
  }
  .el-dialog__headerbtn {
    width: 40px;
    right: 6px;
  }
  .header {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    span {
      font-size: 16px;
      color: #303133;
    }
    .icon {
      margin-right: 22px;
      margin-top: -4px;
      font-size: 15px;
      padding: 8px;
      cursor: pointer;
      color: #909399;
      &:hover {
        color: #409eff;
      }
    }
  }
}
</style>
